<?php
    /**
     * 运行框架
     *
     *
     *
     *
     */

    use EasyWeChat\Foundation\Application;

    defined('IN_NWIDC') or exit('Access Invalid!');
    if (!@include(BASE_DATA_PATH . '/config/config.ini.php')) exit('config.ini.php isn\'t exists!');
    if (file_exists(BASE_PATH . '/config/config.ini.php')) {
        include(BASE_PATH . '/config/config.ini.php');
    }
    global $config;

    //默认平台店铺id
    define('DEFAULT_PLATFORM_STORE_ID', $config['default_store_id']);

    define('URL_MODEL', $config['url_model']);
    define(SUBDOMAIN_SUFFIX, $config['subdomain_suffix']);

    define('SHOP_SITE_URL', $config['shop_site_url']);
    define('CMS_SITE_URL', $config['cms_site_url']);
    define('CIRCLE_SITE_URL', $config['circle_site_url']);
    define('MICROSHOP_SITE_URL', $config['microshop_site_url']);
    define('ADMIN_SITE_URL', $config['admin_site_url']);
    define('MOBILE_SITE_URL', $config['mobile_site_url']);
    define('WAP_SITE_URL', $config['wap_site_url']);
    define('UPLOAD_SITE_URL', $config['upload_site_url']);
    define('RESOURCE_SITE_URL', $config['resource_site_url']);
    define('DELIVERY_SITE_URL', $config['delivery_site_url']);

    define('BASE_DATA_PATH', BASE_ROOT_PATH . '/data');
    define('BASE_UPLOAD_PATH', BASE_DATA_PATH . '/upload');
    define('BASE_RESOURCE_PATH', BASE_DATA_PATH . '/resource');

    define('CHARSET', $config['db'][1]['dbcharset']);
    define('DBDRIVER', $config['dbdriver']);
    define('SESSION_EXPIRE', $config['session_expire']);
    define('LANG_TYPE', $config['lang_type']);
    define('COOKIE_PRE', $config['cookie_pre']);
    define('DBPRE', $config['tablepre']);
    define('DBNAME', $config['db'][1]['dbname']);
    $_GET['act'] = $_GET['act'] ? strtolower($_GET['act']) : ($_POST['act'] ? strtolower($_POST['act']) : null);
    $_GET['op'] = $_GET['op'] ? strtolower($_GET['op']) : ($_POST['op'] ? strtolower($_POST['op']) : null);

    if (empty($_GET['act'])) {
        require_once(BASE_CORE_PATH . '/framework/core/route.php');
        new Route($config);
    }
    //统一ACTION
    $_GET['act'] = preg_match('/^[\w]+$/i', $_GET['act']) ? $_GET['act'] : 'index';
    $_GET['op'] = preg_match('/^[\w]+$/i', $_GET['op']) ? $_GET['op'] : 'index';

    //对GET POST接收内容进行过滤,$ignore内的下标不被过滤
    $ignore = array(
        'article_content',
        'pgoods_body',
        'doc_content',
        'content',
        'sn_content',
        'g_body',
        'store_description',
        'p_content',
        'groupbuy_intro',
        'remind_content',
        'note_content',
        'ref_url',
        'adv_pic_url',
        'adv_word_url',
        'adv_slide_url',
        'appcode',
        'mail_content'
    );
    if (!class_exists('Security')) require(BASE_CORE_PATH . '/framework/libraries/security.php');
    $_GET = !empty($_GET) ? Security::getAddslashesForInput($_GET, $ignore) : array();
    $_POST = !empty($_POST) ? Security::getAddslashesForInput($_POST, $ignore) : array();
    $_REQUEST = !empty($_REQUEST) ? Security::getAddslashesForInput($_REQUEST, $ignore) : array();
    $_SERVER = !empty($_SERVER) ? Security::getAddSlashes($_SERVER) : array();

    //启用ZIP压缩
    if ($config['gzip'] == 1 && function_exists('ob_gzhandler') && $_GET['inajax'] != 1) {
        ob_start('ob_gzhandler');
    } else {
        ob_start();
    }

    if (!isset($_SESSION)) {
        session_start();
    }

    if (($_GET['act'] == 'index' && $_GET['op'] == 'index')) {
        $GLOBALS['in_index'] = 1;
    }

    //如果存在分销插件的话
    //加载分销插件
    $distribute_dir = $_SERVER['DOCUMENT_ROOT'] . "/distribute";
    $open_distribute = false;
    if (file_exists($distribute_dir)) {
        require_once($_SERVER['DOCUMENT_ROOT'] . "/distribute/include/core.php");

        $open_distribute = true;
    }

    function dis_open() {
        global $open_distribute;
        return $open_distribute;
    }

    function tui_open() {
        static $result = null;
        if ($result === null) {
            $result = file_exists(RPlugin::getPackagePath() . DIRECTORY_SEPARATOR . 'tgb');
        }
        return $result;
    }

    function wgroup_open() {
        return file_exists(RPlugin::getPackagePath() . DIRECTORY_SEPARATOR . 'we_groupbuy');
    }


    require_once(BASE_CORE_PATH . '/framework/libraries/queue.php');

    require_once(($_SERVER['DOCUMENT_ROOT']) . '/packages/bootstrap.php');

    //插件系统初始化
    RPlugin::bootstrap(dirname(__DIR__), dirname(__DIR__) . '/packages');



    require_once(BASE_CORE_PATH . '/framework/function/core.php');
    require_once(BASE_CORE_PATH . '/framework/core/base.php');

    require_once(BASE_CORE_PATH . '/framework/function/goods.php');
    //echo dirname(BASE_PATH) . '/packages/bootstrap.php';


    if (function_exists('spl_autoload_register')) {
        spl_autoload_register(array(
            'Base',
            'autoload'
        ));
    } else {
        function __autoload($class) {
            return Base::autoload($class);
        }
    }



    /*
        连接数据库
     */
    $config = include(dirname(dirname(__FILE__)) . '/data/config/config.ini.php');
    $GLOBALS['conn'] = mysqli_connect($config['db'][1]['dbhost'], $config['db'][1]['dbuser'], $config['db'][1]['dbpwd'], $config['db'][1]['dbname']);
    mysqli_query($GLOBALS['conn'], "set names {$config['db'][1]['dbcharset']}");

    /**基础数据库查询函数**/
    function getOne($sql) {
        $res = mysqli_query($GLOBALS['conn'], $sql);
        if (!$res) {
            //echo $sql;
            die($sql);
        }

        $row = mysqli_fetch_row($res);
        return $row ? $row[0] : null;
    }

    function getAll($sql) {
        $res = mysqli_query($GLOBALS['conn'], $sql);
        if (!$res) {
            die($sql);
        }
        $arr = array();
        while ($row = mysqli_fetch_assoc($res)) {
            $arr[] = $row;
        }
        return $arr;
    }

    function getRow($sql) {
        $res = mysqli_query($GLOBALS['conn'], $sql);
        if (!$res) {
            die($sql);
        }
        $row = mysqli_fetch_assoc($res);
        return count($row) ? $row : array();
    }

    /* 常用函数集合 */
    function genTree5($items) {
        foreach ($items as $item)
            $items[$item['gc_parent_id']]['children'][$item['gc_id']] = &$items[$item['gc_id']];
        return isset($items[0]['children']) ? $items[0]['children'] : array();
    }

    /**
     * 得到今天的订单数
     *
     * @return [type] [description]
     */
    function get_today_orders($member_id) {
        $start = strtotime(date('Y-m-d'));
        $m = Model();
        $amount = 0;
        $orders = $m->table('order')->where(array(
            "buyer_id" => $member_id,
            'add_time' => array(
                'time',
                array(
                    $start,
                    $start + 24 * 3600
                )
            )
        ))->select();
        $count = 0;
        $amount = 0;
        foreach ($orders as $order) {
            $m->cls();
            $goods = $m->table('order_goods')->where(array('order_id' => $order['order_id']))->select();
            foreach ($goods as $g) {
                $m->cls();
                $ginfo = $m->table('goods')->where(array('goods_id' => $g['goods_id']))->find();
                if ($ginfo['open_tax'] == 1) {
                    $amount += $order['order_amount'];
                }
            }
        }
        return array(
            $orders ? count($orders) : 0,
            $amount
        );

    }

    function is_proxy($member_id = null) {
        if ($member_id == null) {
            $member_id = $_SESSION['member_id'];
        }
        $m = Model();
        $user = $m->table('proxy')->where(array(
            'member_id' => $member_id,
            'is_buyer'  => 0
        ))->find();
        return $user ? true : false;
    }

    function cal_tax_ex($goods) {

        $model_setting = Model('setting');
        $config = $model_setting->getListSetting();


        // if($goods['goods_price'] < $config['tax_start']){
        // 	return 0;
        // }
        // print_r($goods_detail['goods_info']);
        /**
         * 为啥这么写？我也记不得了
         */
        $exten_info = Model('goods_common')->find($goods['goods_commonid']);
        if(ml("goods_package")->where([
            'goods_id' => $goods['goods_id']
        ])->count()){
            $package = ml('goods_package')->where([
                'goods_id' => $goods['goods_id']
            ])->find();
            if($package){
                $package = unserialize($package['package']);
                $total_tax = 0;
                foreach($package as $item){
                    $ginfo = ml('goods')->find($item['goods_id']);
                    if (!$ginfo) {
                        continue;
                    }
                    if ($ginfo['open_tax'] == 1) {
                       //2017-05-18
                       //$total_tax += (cal_tax_ex($ginfo)*$item['goods_num']);
                       $total_tax += cal_tax_ex($ginfo) * $item['num'];
                       $open_tax = true;
                    }
                }
                return $total_tax;
            }
        }
        if ($config['open_tax'] == 1 && $goods['open_tax'] == 1) {
            $tax = preg_replace_callback("/{\s*(\w+)\s*}/", function ($matched) use (&$goods, $exten_info) {

                $goods['goods_costprice'] = empty($exten_info['goods_costprice']) ? 0 : $exten_info['goods_costprice'];
                switch ($matched[1]) {
                    case 'source_price':
                        return $exten_info['goods_costprice'];
                    case 'goods_price':
                        return $goods['goods_price'];
                    case 'rate':
                        return empty($exten_info['tax']) ? 0 : $exten_info['tax'];
                    default:
                        return 0;
                }
            }, $config['tax_formula']);
            eval('$tax = ' . $tax . ';');
            return round($tax,2);
        }
        return 0;
    }

    function cal_tax(&$cart_list, $tax_free = false) {
        $model_setting = Model('setting');
        $config = $model_setting->getListSetting();
        $total_tax = 0;
        foreach ($cart_list as &$goods) {
            $goods['source_price'] = $goods['goods_price'];
            $g = Model('goods')->find($goods['goods_id']);
            $goods['open_tax'] = $g['open_tax'] ? 1 : 0;
            $goods['reduce'] = $goods['source_price'] - $goods['goods_price'];
        }

        //先把代理价格处理一遍
        foreach ($cart_list as &$goods) {
//            $goods['goods_proxy'] = cal_proxy($goods['goods_price'], $_SESSION['member_id']);
//            $goods['reduce'] = $goods['goods_price'] - $goods['goods_proxy'];
            $goods['goods_proxy'] = $goods['goods_price'];
            $goods['reduct'] = 0;
        }


        if ($config['open_tax'] == 1) {
            $model = Model('goods');
            if (count($cart_list)) {
                $tax_goods = array();
                $total_price = 0;
                foreach ($cart_list as &$goods) {
                    $this_price = $goods['goods_price'] * $goods['goods_num'];
                    $goods_info = $model->find($goods['goods_id']);
                    $exten_info = Model()->table('goods_common')->where(array('goods_commonid' => $goods_info['goods_commonid']))->find();
                    // print_r($exten_info);
                    $goods_info['goods_costprice'] = empty($exten_info['goods_costprice']) ? 0 : $exten_info['goods_costprice'];
                    // echo $goods_info['goods_costprice'];
                    // $ginfo =

                    /***********************************/
                    /**
                     * 为啥这么写？我也记不得了
                     */
                    if (ml("goods_package")->where([
                        'goods_id' => $goods['goods_id']
                    ])->count()
                    ) {
                        $package = ml('goods_package')->where([
                            'goods_id' => $goods['goods_id']
                        ])->find();
                        if ($package) {
                            $package = unserialize($package['package']);
                            $_ttax = 0;
                            foreach ($package as $item) {
                                //2017-05-18
                                $item['num'] = isset($item['num']) ? $item['num'] : 1;
                                $ginfo = ml('goods')->find($item['goods_id']);
                                if (!$ginfo) {
                                    continue;
                                }
                                if ($ginfo['open_tax'] == 1) {
                                    //2017-05-18
                                    //$tax =  cal_tax_ex($ginfo);
                                    $tax = cal_tax_ex($ginfo) * $item['num'];
                                    $_ttax += $tax;
                                    $open_tax = true;
                                }
                            }
                            if ($_ttax > 0) {
                                $goods['tax'] = $_ttax;
                                $new_price = $_ttax + $goods['goods_price'];
                                if (isset($goods['goods_total'])) {
                                    $goods['goods_total'] += ($_ttax - $goods['reduce']) * $goods['goods_num'];
                                }
                                $total_price += $new_price * $goods['goods_num'];
                                $total_tax += ($_ttax - $goods['reduce']) * $goods['goods_num'];

                            }
                        }
                        continue;
                    }
                    /**************************************/

                    //如果这是个保税商品
                    if ($goods_info['open_tax'] == 1) {
                        //计算每个商品的税金
                        $tax = preg_replace_callback("/{\s*(\w+)\s*}/", function ($matched) use ($goods_info, $this_price, &$goods, &$exten_info) {
                            switch ($matched[1]) {
                                case 'source_price':
                                    return $exten_info['goods_costprice'];
                                case 'goods_price':
                                    return $goods['goods_price'];
                                case 'rate':
                                    return $exten_info['tax'];
                                default:
                                    return 0;
                            }
                        }, $config['tax_formula']);
                        eval('$tax = ' . $tax . ';');
                        $tax = round($tax, 2);
                        $goods['tax'] = $tax;
                        $new_price = $tax + $goods['goods_price'];
                        if (isset($goods['goods_total'])) {
                            $goods['goods_total'] += ($tax - $goods['reduce']) * $goods['goods_num'];
                        }
                        $total_price += $new_price * $goods['goods_num'];
                        $total_tax += ($tax - $goods['reduce']) * $goods['goods_num'];
                    }
                }

                // 这里暂时不计算免税

                //如果触发了免税条件

                /*
                 * 现在似乎没有免税了
                if ($tax_free) {
                    if ($total_price < $config['tax_start'] && $total_tax < $config['tax_start_else']) {
                        foreach ($cart_list as &$goods) {
                            if (isset($goods['tax'])) {
                                // $goods['goods_price'] -= $goods['tax'];
                                if (isset($goods['goods_total'])) {
                                    $goods['goods_total'] -= $goods['tax'];
                                }
                                $goods['tax'] = 0;
                                // unset($goods['tax']);
                            }
                        }
                        $total_tax = 0;
                    }
                }
                */
            }
        }



        return $total_tax;

    }

    function cal_proxy($price, $member_id, $next_formula = null) {
        if (is_mobile()) {
            return $price;
        }
        if (!is_proxy()) {
            return $price;
        }
        $config = Model();
        $gold_formula = $config->table('setting')->where(array('name' => 'gold_formula'))->find();
        $gold_formula = $gold_formula['value'];
        if (empty($gold_formula)) {
            $gold_price = $price;
        } else {
            $formula = preg_replace_callback("/{\s*(\w+)\s*}/", function ($matched) use (&$price) {
                switch ($matched[1]) {
                    case 'price':
                        return $price;

                    default :
                        return 1;
                }
            }, $gold_formula);
            try {
                eval('$gold_price = ' . $formula . ';');
            } catch (Exception $e) {
                $gold_price = $price;
            }
        }
        $m = &$config;
        $arr = array();
        $count = 0;
        // $member_id = $_SESSION['member_id'];
        while (true) {
            $m->cls();
            $proxy = $m->table('proxy')->where(array('member_id' => $member_id))->find();

            if (!$proxy) {
                break;
            }

            if ($count) {
                $arr[] = $proxy['price_formula'];
            }

            $member_id = $proxy['parent_id'];

            if ($proxy['parent_id'] == 0) {
                break;
            }
            $count++;
        }
        $arr = array_reverse($arr);
        $max_price = $price;
        $current_price = $gold_price;
        foreach ($arr as $formula) {
            if (empty($formula)) {
                continue;
            }
            $formula = preg_replace_callback("/{\s*(\w+)\s*}/", function ($matched) use (&$current_price, &$max_price) {
                switch ($matched[1]) {
                    case 'current_price':
                        return $current_price;

                    case 'max_price' :
                        return $max_price;
                }
            }, $formula);

            $backup = $current_price;

            try {
                eval('$current_price = ' . $formula . ';');
            } catch (Exception $e) {
                $current_price = $backup;
            }
        }

        if ($next_formula) {
            $formula = preg_replace_callback("/{\s*(\w+)\s*}/", function ($matched) use (&$current_price, &$max_price) {
                switch ($matched[1]) {
                    case 'current_price':
                        return $current_price;

                    case 'max_price' :
                        return $max_price;
                }
            }, $next_formula);
            $backup = $current_price;

            try {
                eval('$current_price = ' . $formula . ';');
            } catch (Exception $e) {
                $current_price = $backup;
            }
        }


        return round($current_price, 2);

    }

    function get_split_order($goods) {
        $config = Model('setting')->getListSetting();
        $item = array();
        $orders = array();
        $limit = 0;
        $simple_order = array();
// for($i = 0; $i < count($goods); $i++){
        foreach ($goods as $i => $g) {
            // $g = $goods[$i];
            $n = $g['goods_num'];
            if ($g['open_tax'] == 0) {
                $simple_order[$g['goods_id']] = $g;
                continue;
            }

            $goods_info = Model('goods')->find($g['goods_id']);

            if ($goods_info['open_tax'] != 1) {
                $simple_order[$g['goods_id']] = $g;
                continue;
            }
            //凡是单个保税商品的税费超过设定的，这些就单独成一个订单
            if ($g['tax'] > $config['tax_start_else']) {
                $item[$g['goods_id']] = $g;
                $orders[] = $item;
                $item = array();
                $limit = 0;
                continue;
            }
            while ($g['goods_num']) {
                if ($limit + $g['tax'] <= $config['split_limit']) {
                    $limit += $g['tax'];
                    // echo $limit;
                    $g['goods_num']--;
                    if (!isset($item[$g['goods_id']])) {
                        $item[$g['goods_id']] = $g;
                        $item[$g['goods_id']]['goods_num'] = 1;
                    } else {
                        $item[$g['goods_id']]['goods_num']++;
                    }
                } else {
                    if (count($item) == 0) {
                        $g['goods_num']--;
                        $item[$g['goods_id']] = $g;
                        $item[$g['goods_id']]['goods_num'] = 1;
                        $orders[] = $item;
                        $limit = 0;
                        $item = array();
                        continue;
                    }
                    $orders[] = $item;
                    $item = array();
                    $limit = 0;
                }
            }
        }
        if (count($simple_order)) {
            $orders[] = $simple_order;
        }
        if (count($item)) {
            $orders[] = $item;
        }


        return $orders;
    }

    function cal_free_tax(&$orders) {
        $config = Model('setting')->getListSetting();
        foreach ($orders as &$order) {
            $total_tax = 0;
            $total_price = 0;
            array_filter($order, function ($item) use (&$total_tax, &$total_price) {
                $total_tax += $item['tax'] * $item['goods_num'];
                $total_price += $item['goods_total'];
            });
            if ($total_price < $config['tax_start'] && $total_tax < $config['tax_start_else']) {
                // $orders['tax'] = $total_tax;
                foreach ($order as &$goods) {
                    $goods['goods_total'] = ($goods['goods_price'] - $goods['reduce']) * $goods['goods_num'];
                    $goods['tax'] = 0;
                }
                $order = array(
                    'total_tax'  => $total_tax,
                    'tax'        => 0,
                    'store_name' => $order[0]['store_name'],
                    'goods'      => $order,
                );
            } else {
                $order = array(
                    'total_tax'  => $total_tax,
                    'tax'        => $total_tax,
                    'store_name' => $order[0]['store_name'],

                    'goods' => $order
                );
            }
        }
    }


    function get_order_count($member_id, $address_id) {
        $today_start = strtotime(date("Ymd"));
        $week_start = strtotime("this Monday");
        $month_start = strtotime(date('Ym'));
        $year_start = strtotime(date('Y'));
        $months = array(
            '31' => array(
                1,
                3,
                5,
                7,
                8,
                10,
                12
            ),
            30   => array(
                4,
                6,
                9,
                11
            ),
            28   => array(2),
        );
        $month = (int)date('m');
        $year_end = 24 * 3600 * 365;
        if ($month == 2) {
            $year = strtotime(date('Y'));
            if ($year % 4 == 0 && $year % 100) {
                $month_end = $month_start + 29 * 24 * 3600;
            }
        }
        foreach ($months as $key => $m) {
            if (in_array($month, $m)) {
                $month_end = $month_start + $key * 24 * 3600;
                break;
            }
        }
        $condition = array(
            array(
                $today_start,
                strtotime("+ 1 day", $today_start)
            ),
            array(
                $week_start,
                strtotime("+ 7 days", $week_start)
            ),
            array(
                $month_start,
                $month_end
            ),
            array(
                $year_start,
                strtotime("+ 1 year", $year_start)
            ),
        );

        $ret = array();
        $uinfo = Model('member')->find($member_id);
        $idcard = $uinfo['idcard'];
        $ainfo = Model('address')->where(array('address_id' => $address_id))->find();
        $phone = $ainfo['mob_phone'];
        $address = $ainfo['area_info'] . ' ' . $ainfo['address'];
        $receiver_name = $ainfo['true_name'];
        foreach ($condition as $con) {
            $sql = "select count(*) as num,sum(order_amount) as total from ra_order where
    				(order_state = 20 or order_state = 30 or order_state = 10)
    				and add_time > $con[0]
    				and add_time < $con[1]
                    and is_tax_order = 1
    				and (
						idcard = '$idcard'
						or phone = '$phone'
						or address = '$address'
						or receiver_name = '$receiver_name'
    				)";

            $res = Model()->query($sql);
            $ret[] = $res[0];
        }

        $last_order_time = Model()->query("select add_time from ra_order where is_tax_order = 1 and buyer_id = " . $member_id . ' order by add_time desc');
        if (!$last_order_time) {
            $last_order_time = 0;
        } else {
            $last_order_time = $last_order_time[0]['add_time'];
        }
        $ret[] = $last_order_time;

        return $ret;


    }


    function getReciverAddr($address_info = array()) {
        if (intval($address_info['dlyp_id'])) {
            $reciver_info['phone'] = trim($address_info['dlyp_mobile'] . ($address_info['dlyp_telephony'] ? ',' . $address_info['dlyp_telephony'] : null), ',');
            $reciver_info['tel_phone'] = $address_info['dlyp_telephony'];
            $reciver_info['mob_phone'] = $address_info['dlyp_mobile'];
            $reciver_info['address'] = $address_info['dlyp_area_info'] . ' ' . $address_info['dlyp_address'];
            $reciver_info['area'] = $address_info['dlyp_area_info'];
            $reciver_info['street'] = $address_info['dlyp_address'];
            $reciver_info['dlyp'] = 1;
            $reciver_info = serialize($reciver_info);
            $reciver_name = $address_info['dlyp_address_name'];
        } else {
            $reciver_info['phone'] = trim($address_info['mob_phone'] . ($address_info['tel_phone'] ? ',' . $address_info['tel_phone'] : null), ',');
            $reciver_info['mob_phone'] = $address_info['mob_phone'];
            $reciver_info['tel_phone'] = $address_info['tel_phone'];
            $reciver_info['address'] = $address_info['area_info'] . ' ' . $address_info['address'];
            $reciver_info['area'] = $address_info['area_info'];
            $reciver_info['street'] = $address_info['address'];
            $reciver_info = serialize($reciver_info);
            $reciver_name = $address_info['true_name'];
        }
        return array(
            $reciver_info,
            $reciver_name
        );
    }

    function order_can_split() {
        return isset($_SESSION['want_split']);
    }

    function require_wechat() {
        require_once(dirname(BASE_PATH) . '/wechat/index.php');
    }

    function check_mobile_code($mobile, $code = null) {
        $mobile = trim($mobile);
        if ($code) {
            $code = trim($code);
        }
        $config = Model('setting')->getListSetting();
        if ($config['open_phone_message'] == 0) {
            if ($mobile == null) {
                return true;
            }
            return $mobile == $_SESSION['mobile_code']['mobile'];
        } else {
            if ($mobile == null) {
                return $code == $_SESSION['mobile_code']['code'];
            }
            return $mobile == $_SESSION['mobile_code']['mobile'] && $code == $_SESSION['mobile_code']['code'];
        }
    }


    function _get_token($member_id, $member_name, $client) {
        $model_mb_user_token = Model()->table('mb_user_token');

        //重新登录后以前的令牌失效
        //暂时停用
        $condition = array();
        $condition['member_id'] = $member_id;
        $condition['client_type'] = $_POST['client'];
        $model_mb_user_token->where($condition)->delete();

        //生成新的token
        $mb_user_token_info = array();
        $token = md5($member_name . strval(TIMESTAMP) . strval(rand(0, 999999)));
        $mb_user_token_info['member_id'] = $member_id;
        $mb_user_token_info['member_name'] = $member_name;
        $mb_user_token_info['token'] = $token;
        $mb_user_token_info['login_time'] = TIMESTAMP;
        $mb_user_token_info['client_type'] = $client;

        // print_R($mb_user_token_info);
        $_SESSION['member_id'] = $member_id;

        $result = $model_mb_user_token->insert($mb_user_token_info);

        if ($result) {
            return $token;
        } else {
            return null;
        }

    }

    function isMobile() {

        // 如果有HTTP_X_WAP_PROFILE则一定是移动设备
        if (isset ($_SERVER['HTTP_X_WAP_PROFILE'])) {
            return true;
        }
        // 如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
        if (isset ($_SERVER['HTTP_VIA'])) {
            // 找不到为flase,否则为true
            return stristr($_SERVER['HTTP_VIA'], "wap") ? true : false;
        }
        // 脑残法，判断手机发送的客户端标志,兼容性有待提高
        if (isset ($_SERVER['HTTP_USER_AGENT'])) {
            $clientkeywords = array(
                'nokia',
                'sony',
                'ericsson',
                'mot',
                'samsung',
                'htc',
                'sgh',
                'lg',
                'sharp',
                'sie-',
                'philips',
                'panasonic',
                'alcatel',
                'lenovo',
                'iphone',
                'ipod',
                'blackberry',
                'meizu',
                'android',
                'netfront',
                'symbian',
                'ucweb',
                'windowsce',
                'palm',
                'operamini',
                'operamobi',
                'openwave',
                'nexusone',
                'cldc',
                'midp',
                'wap',
                'mobile'
            );
            // 从HTTP_USER_AGENT中查找手机浏览器的关键字
            if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT']))) {
                return true;
            }
        }
        // 协议法，因为有可能不准确，放到最后判断
        if (isset ($_SERVER['HTTP_ACCEPT'])) {
            // 如果只支持wml并且不支持html那一定是移动设备
            // 如果支持wml和html但是wml在html之前则是移动设备
            if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html')))) {
                return true;
            }
        }
        return false;
    }


    function get_mobile_member_info() {
        if (!isset($_COOKIE['key'])) {
            return false;
        }
        $key = $_COOKIE['key'];
        $minfo = Model('mb_user_token')->where(array('token' => $key))->find();
        if ($minfo) {
            $minfo = Model('member')->find($minfo['member_id']);
            return $minfo;
        }
        return null;
    }

    function require_mobile_interface() {
        $config = include(BASE_ROOT_PATH . '/data/config/config.ini.php');
        @require_once(BASE_ROOT_PATH . '/message/' . $config['message_interface'] . '.php');
        @$ins = new $config['message_interface']();
        return array(
            $ins,
            $config['message_format'],
            $config['mobile_code']
        );
    }


    $template_type = null;
    function templet($where, $type = null) {

        $_path = BASE_PATH . '/templates/' . _config('template_name') . '/' . _config('template_name') . '.' . $where . '.php';
        $GLOBALS['template_type'] = $type;
        return $_path;
    }

    function _config($name) {
        static $config = null;
        if ($config == null) {
            $config = Model('setting')->getListSetting();
        }
        return $config[$name];
    }

    function get_template_type() {
        return $GLOBALS['template_type'];
    }


    function has_templet() {
        static $has_import = 0;
        return $has_import++ > 0;
    }

    function get_nav() {
//    $temp = get_template_package();
//    print_r($temp);
        $ret = array();
        if ($_GET['act'] == 'index' && $_GET['op'] == 'show_place' || $_GET['act'] == 'brand' && $_GET['op'] == 'list') {
            if ($_SESSION['place']) {
                $info = $_SESSION['place'];
            } elseif (cookie('place')) {
                $info = Model('place')->find(cookie("place"));
            }

//        if($info){
//            $ret[] = $info['name'] . '首页';
//        }
//        else{
//            if (_config('template_name') == 'mln') {
//                $ret[] = "首页/D'accueil";
//            }
//            else{
//                $ret[] = '首页';
//            }
//        }
        }

//    if(!count($ret)){
//        if (_config('template_name') == 'mln') {
//            $ret[] = "首页/D'accueil";
//        }
//        else{
//            $ret[] = '首页';
//        }
//    }

        $nav = Model()->table('navigation')->where(array('nav_location' => 1))->order('nav_sort asc')->select();
        $sec = array();

        if ($_GET['act'] == 'index' && $_GET['op'] == 'show_place' || $_GET['act'] == 'brand' && $_GET['op'] == 'list') {
            $sec = Model()->table('brand')->where(array(
                'from_place'      => $info['id'],
                'brand_recommend' => 1
            ))->order('brand_sort asc')->select();
            $arr = array();
            foreach ($sec as $key => $val) {
                $arr[] = array(
                    'nav_title' => $val['brand_name'],
                    'nav_url'   => '/shop/?act=brand&op=list&brand=' . $val['brand_id']
                );
                $sec = $arr;
            }
        } else {
        }

        $ret[] = array_merge($sec, $nav);
        return $ret;

    }

    function login_member($member_id) {
        require_once(dirname(BASE_PATH) . '/shop/control/login.php');
        $login = new loginControl();
        $login->superLogin($member_id);
    }

    function get_places() {
        return Model('place')->select();
    }


    /**
     * 获得模板的列表
     */
    function get_template_package() {
        $path = dirname(BASE_PATH) . '/shop/templates/';
        $list = glob($path . '*');
        $ret = array();
        foreach ($list as $li) {
            $file_name = basename($li);
            if (!is_dir($li) || $file_name == 'default') {
                continue;
            }
            //读出package.json
            try {
                $json = file_get_contents($li . '/package.json');
                $json = preg_replace("/\/\*[\s\S]+?\*\//", "", $json);
                $item = json_decode($json, true);
                $item['__name'] = $file_name;
                $ret[] = $item;
            } catch (Exception $e) {

            }
        }
        return $ret;
    }

    //tpl_get("header,logo");
    function tpl_get($item) {
        static $config = null;
        static $images = null;
        if ($config == null) {
            $web_cofig = Model('setting')->getListSetting();
            $config = file_get_contents(dirname(BASE_PATH) . '/shop/templates/' . $web_cofig['template_name'] . '/images.json');
            $images = json_decode($config, true);
        }

        if (isset($images[$item]['template'])) {
            return $images[$item]['items'];
        } else {
            return $images[$item];
        }
    }


    function is_mobile() {
        return get_mobile_member_info();
    }

    function require_wechat_js($onlyjs = false,$url = '') {
        require_wechat();
        $wechat = new Wechat(-1);
        require $_SERVER['DOCUMENT_ROOT'] . '/vendor/autoload.php';
        $config = (object)$wechat->config;
        $options = [
            'debug' => false,

            'app_id'  => $config->appid,
            // AppID
            'secret'  => $config->appsecret,
            // AppSecret
            'token'   => 'yhg_weixin_token',
            // Token
            'aes_key' => 'LUxtl0VqoHRcd3hkePAGrnj2HjxtJmmroXpQUHWFFoT',


            // 'aes_key' => null, // 可选

            'log' => [
                'level' => 'debug',
                'file'  => '/tmp/easywechat.log',
                // XXX: 绝对路径！！！！
            ],

            'guzzle' => [
                'timeout' => 3.0,
                // 超时时间（秒）
                'verify'  => false,
                // 关掉 SSL 认证（强烈不建议！！！）
            ],

            //...
        ];

        $app = new Application($options);

        $js = $app->js;
        $apis = array(
            'checkJsApi',
            'onMenuShareTimeline',
            'onMenuShareAppMessage',
            'onMenuShareQQ',
            'onMenuShareWeibo',
            'hideMenuItems',
            'showMenuItems',
            'hideAllNonBaseMenuItem',
            'showAllNonBaseMenuItem',
            'translateVoice',
            'startRecord',
            'stopRecord',
            'onRecordEnd',
            'playVoice',
            'pauseVoice',
            'stopVoice',
            'uploadVoice',
            'downloadVoice',
            'chooseImage',
            'previewImage',
            'uploadImage',
            'downloadImage',
            'getNetworkType',
            'openLocation',
            'getLocation',
            'hideOptionMenu',
            'showOptionMenu',
            'closeWindow',
            'scanQRCode',
            'chooseWXPay',
            'openProductSpecificView',
            'addCard',
            'chooseCard',
            'openCard'
        );

        if ($onlyjs) {
            echo $js->config($apis, false,false,true,$url);
            return;
        }
        ?>
        <script>
            define = null;
            require = null;
        </script>
        <script src="https://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>

        <script>
            wx.config(
                <?php echo $js->config($apis, false) ?>
            );
        </script>
        <?php
    }

    function is_wechat() {
        $user_agent = $_SERVER['HTTP_USER_AGENT'];
        return (strpos($user_agent, 'MicroMessenger') !== false);
    }


?>
